package teamgodeater.hicarnet.MVP.Ui.Main;

import android.graphics.Point;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;

import teamgodeater.hicarnet.Activity.ManageActivity;
import teamgodeater.hicarnet.Help.ConditionTask;
import teamgodeater.hicarnet.Help.UserDataHelp;
import teamgodeater.hicarnet.R;
import teamgodeater.hicarnet.Utils.Utils;

import static teamgodeater.hicarnet.Activity.ManageActivity.manageActivity;

/**
 * Created by G on 2016/6/20 0020.
 */

public class MapPresent extends MainContractor.MapPresent implements BaiduMap.OnMapLoadedCallback, BaiduMap.OnMapTouchListener, ManageActivity.OnLocReceiverObserve {
    public TextureMapView mapView;
    public BaiduMap baiduMap;

    private Handler handler;
    private Marker myLocMarker;
    private MainPresent mDspPresenter;
    private ConditionTask firstTask;

    @Override
    public void zoomToFit() {
        if ( mDspPresenter.gasStationPresent.interceptZoomToFit() ||
                mDspPresenter.mapSearchPresent.interceptZoomToFit())
            return;
        zoomToMyLoc();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDspPresenter = null;
    }

    @Override
    protected void onStart() {
        firstTask = new ConditionTask(2, new Runnable() {
            @Override
            public void run() {
                UserDataHelp.getUserPointData(null);
                zoomToMyLoc();
            }
        });
        mDspPresenter = mView.mPresenter;
        handler = new Handler();
//        getGlfLst();
        //添加百度地图
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mapView = manageActivity.getMainMapView();
        mView.mRootContain
                .addView(mapView, 0, params);
        //设置百度地图
        baiduMap = mapView.getMap();
        baiduMap.showMapPoi(true);
        //设置百度监听
        baiduMap.setOnMapLoadedCallback(this);
        baiduMap.setOnMapTouchListener(this);
        //设置定位监听观察者
        manageActivity.setLocReceiverObserve(this);
    }


    @Override
    public void onMapLoaded() {
        requestMapControlPosition();
        firstTask.excute();
    }


    /**
     * 隐藏地图控制器Runnable
     */
    Runnable hideMapControlRunnable = new Runnable() {
        @Override
        public void run() {
            hideMapControlButton();
        }
    };

    private void hideMapControlButton() {
        mView.zoomLocButton.setVisibility(View.INVISIBLE);
        mapView.showZoomControls(false);
    }

    private void showMapControlButton() {
        mView.zoomLocButton.setVisibility(View.VISIBLE);
        mapView.showZoomControls(true);
    }


    @Override
    public void onTouch(MotionEvent motionEvent) {
        int action = motionEvent.getAction();

        if (gMapTouchListener !=null)
            gMapTouchListener.OnTouch(action);

        if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) {
            handler.removeCallbacks(hideMapControlRunnable);
            showMapControlButton();
        }
        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
            handler.removeCallbacks(hideMapControlRunnable);
            handler.postDelayed(hideMapControlRunnable, 3000);
        }
    }


    @Override
    public void onReceiveLoc(BDLocation loc) {
        if (manageActivity.getMyLocation() != null) {
            requestLocMarket();
            firstTask.excuteOnce();
        }
    }

    private void requestLocMarket() {
        if (locVisible)
            if (myLocMarker == null) {
                OverlayOptions ooD = new MarkerOptions().position(Utils.getLatLng(manageActivity.getMyLocation()))
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.loc_0)).zIndex(0);
                myLocMarker = (Marker) (baiduMap.addOverlay(ooD));
            } else {
                myLocMarker.setPosition(Utils.getLatLng(manageActivity.getMyLocation()));
            }
    }


    public Point getMapCenterPoint() {
        return new Point(mView.mRootContain.getWidth() / 2
                , mView.searchView.getBottom() + (mView.viewPagerFramelayout.getTop()
                + (int) mView.viewPagerFramelayout.getTranslationY()
                - mView.searchView.getBottom()) / 2 + Utils.dp2Px(8));
    }


    private void zoomToMyLoc() {
        if (manageActivity.getMyLocation() == null) {
            Utils.toast("定位失败 请检查你的网络设置");
            return;
        }
        LatLng latLng = Utils.getLatLng(manageActivity.getMyLocation());
        float zoom = 14f;
        if (!hasFirstShow) {
            zoom = 11f;
        }
        zoomToTarget(latLng, zoom);
    }

    public void zoomToTarget(LatLng latLng, float zomm) {
        MapStatus status;
        Point mapCenterPoint = getMapCenterPoint();
        status = new MapStatus.Builder().target(latLng)
                .targetScreen(mapCenterPoint).rotate(45).overlook(0).zoom(zomm).build();
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(status);
        baiduMap.animateMapStatus(mapStatusUpdate, 800);
    }

    /**
     * 改变地图控制器位置 适应当前屏幕
     */
    public void requestMapControlPosition() {
        int left = mView.viewPagerFramelayout.getLeft();
        int top = mView.searchView.getBottom();
        int bottom = (int) mView.viewPagerFramelayout.getY();
        int right = mView.viewPagerFramelayout.getRight();
        Point scaleControlPoint = new Point(left, bottom - Utils.dp2Px(16));
        Point ZoomControlsPoint = new Point(right - Utils.dp2Px(40), top - Utils.dp2Px(60) + (bottom - top) / 2);
        mapView.setZoomControlsPosition(ZoomControlsPoint);
        mapView.setScaleControlPosition(scaleControlPoint);
        handler.post(hideMapControlRunnable);
    }

    boolean locVisible = true;

    public void setMyLocVisible(boolean visible) {
        if (visible) {
            locVisible = true;
            requestLocMarket();
        } else {
            locVisible = false;
            if (myLocMarker != null) {
                myLocMarker.remove();
                myLocMarker = null;
            }
        }
    }

    private OnGMapTouchListener gMapTouchListener;

    public void setOnMapTouchListener(OnGMapTouchListener listener) {
        gMapTouchListener = listener;
    }

    public interface OnGMapTouchListener {
        void OnTouch(int action);
    }

    boolean hasFirstShow = false;

    public void mapFristShow() {
        if (hasFirstShow)
            return;
        hasFirstShow = true;
        zoomToMyLoc();
    }

}
